/**
 * @fileoverview This loader define a top level 'cometd' variable for bootstraping a YUI3 instance
 */
if (typeof(comet) === 'undefined') {
    var comet = {
        loaded:false,
        //TODO enhance it to allow users to override YUI configurations
        YUI : function(cfg) {
            if (typeof(YUI) === 'undefined' && !comet.loaded) {
                var w = window.d = document,l = d.location,ld = 'yui.yahooapis.com/3.0.0pr2/build/yui/yui-min.js';
                var _s = d.createElement('script');
                //_s.src = 'http' + (l.location == 'https' ? 's' : '') + '://' + ld;
                _s.src = (cfg && cfg.base) ? cfg.base + 'yui/yui-min.js' : 'http://' + ld;
                d.getElementsByTagName('head')[0].appendChild(_s);
                comet.loaded = true;
            }

            return {
                cfg:cfg,
                args:null,
                use:function() {
                    this.args = arguments
                    if (typeof(YUI) === 'undefined') {
                        var that = this;

                        function delegate() {
                            that.use.apply(that, that.args);
                        }

                        window.setTimeout(delegate, 500)
                    } else {
                        var merged = comet.getProfile(cfg ? cfg.cometBase : null)
                        YUI().use(function(Y) {
                            merged = Y.merge(merged, cfg)
                        })
                        var yui = YUI(merged)
                        yui.log('created YUI instance, cometBase: ' + merged.cometBase + ', base: ' + merged.base, 'debug', 'comet')
                        YUI.use.apply(yui, arguments);
                    }
                }
            }
        },

        //TODO allow user to specify a variable to override the cometd base path
        getProfile:function(base) {
            base = (base) ? base : 'http://yui-comet.googlecode.com/svn/trunk/web-app/js/cometd-yui3/'
            return {base:"http://yui.yahooapis.com/3.0.0pr2/build/", timeout: 10000,
                modules: {
                    'io-chain':{
                        fullpath: base + 'io-chain.js', type:'js',requires:['io-base']
                    },
                    'comet':{
                        fullpath:base + 'cometd-yui3.js', type:'js',
                        requires:['base', 'io-base','io-queue','io-chain', 'node', 'json','queue','cookie','substitute']
                    }
                }}
        }
    };
}
